<template>
  <div class="admin-orders-container">
    <div class="page-header">
    <h2>订单管理</h2>
      <div class="header-actions">
        <el-button type="success" @click="exportAllOrders" :loading="exporting" class="export-btn">
          <el-icon><Download /></el-icon> 导出订单
        </el-button>
        <el-input
          v-model="searchQuery"
          placeholder="搜索订单号或商品"
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
          class="search-input"
        />
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
          class="date-picker"
        />
        <el-select v-model="statusFilter" placeholder="订单状态" clearable @change="handleSearch" class="status-select">
          <el-option label="全部" value="" />
          <el-option label="待处理" value="pending" />
          <el-option label="已支付" value="paid" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
          <el-option label="已退款" value="refunded" />
        </el-select>
        <el-select v-model="channelFilter" placeholder="销售渠道" clearable @change="handleSearch" class="channel-select">
          <el-option label="全部" value="" />
          <el-option v-for="channel in channels" :key="channel.id" :label="channel.name" :value="channel.id" />
        </el-select>
      </div>
    </div>

    <el-table
      :data="orders"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="orderNo" label="订单号" width="180" class-name="text-left" />
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="total" label="金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.total.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="channel" label="渠道" width="120">
        <template #default="scope">
          {{ scope.row.channel ? scope.row.channel.name : '店内' }}
        </template>
      </el-table-column>
      <el-table-column prop="user" label="操作员" width="120">
        <template #default="scope">
          {{ scope.row.user ? scope.row.user.name || scope.row.user.username : '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="420">
        <template #default="scope">
          <div class="action-buttons">
            <el-button size="small" @click="viewOrder(scope.row)">查看</el-button>
            <el-button
              size="small"
              type="primary"
              @click="printOrder(scope.row)"
              :disabled="scope.row.status === 'cancelled'"
            >
              打印
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="cancelOrder(scope.row)"
              :disabled="scope.row.status === 'cancelled' || scope.row.status === 'refunded'"
            >
              取消
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="completeOrder(scope.row)"
              :disabled="scope.row.status === 'completed' || scope.row.status === 'cancelled' || scope.row.status === 'refunded'"
            >
              完成
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="refundOrder(scope.row)"
              :disabled="scope.row.status === 'cancelled' || scope.row.status === 'refunded' || scope.row.status === 'pending'"
            >
              退款
            </el-button>
            <el-button
              size="small"
              type="info"
              @click="exportOrder(scope.row)"
            >
              导出
            </el-button>
          </div>
        </template>
      </el-table-column>
      
      <!-- 空数据状态显示 -->
      <template #empty>
        <div class="empty-data">
          <el-icon><Box /></el-icon>
          <p>暂无订单数据</p>
        </div>
      </template>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="orderDialogVisible"
      width="70%"
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="order-header">
          <div class="order-info">
            <p><strong>订单号：</strong>{{ currentOrder.orderNo }}</p>
            <p><strong>创建时间：</strong>{{ formatDateTime(currentOrder.createdAt) }}</p>
            <p><strong>状态：</strong>{{ getStatusText(currentOrder.status) }}</p>
          </div>
          <div class="order-customer">
            <p><strong>渠道：</strong>{{ currentOrder.channel ? currentOrder.channel.name : '店内' }}</p>
            <p><strong>操作员：</strong>{{ currentOrder.user ? currentOrder.user.name || currentOrder.user.username : '未知' }}</p>
          </div>
        </div>

        <el-table :data="currentOrder.items" border style="width: 100%; margin-top: 20px;">
          <el-table-column prop="product.name" label="商品" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="price" label="单价" width="120">
            <template #default="scope">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="order-summary">
          <p><strong>备注：</strong>{{ currentOrder.note || '无' }}</p>
          <p class="total"><strong>总计：</strong>¥{{ currentOrder.total.toFixed(2) }}</p>
        </div>

        <div class="payment-info" v-if="currentOrder.payments && currentOrder.payments.length > 0">
          <h3>支付信息</h3>
          <el-table :data="currentOrder.payments" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="method" label="支付方式">
              <template #default="scope">
                {{ getPaymentMethod(scope.row.method) }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额">
              <template #default="scope">
                ¥{{ scope.row.amount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getPaymentStatusType(scope.row.status)">
                  {{ getPaymentStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="时间">
              <template #default="scope">
                {{ formatDateTime(scope.row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="printOrder(currentOrder)">打印订单</el-button>
          <el-button 
            type="warning" 
            @click="updateOrderStatus(currentOrder.id, 'completed')"
            v-if="currentOrder && currentOrder.status === 'paid'"
          >
            标记为已完成
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Box, Download } from '@element-plus/icons-vue'
import api from '@/utils/api'
import * as XLSX from 'xlsx'

// 状态数据
const loading = ref(false)
const exporting = ref(false)
const orders = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const searchQuery = ref('')
const dateRange = ref([])
const orderDialogVisible = ref(false)
const currentOrder = ref(null)
const statusFilter = ref('')
const channelFilter = ref('')
const channels = ref([])

// 获取渠道列表
const fetchChannels = async () => {
  try {
    const response = await api.get('/channels')
    if (response.data && response.data.success) {
      channels.value = response.data.data
    }
  } catch (error) {
    console.error('获取渠道列表失败:', error)
  }
}

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = new URLSearchParams({
      page: currentPage.value,
      limit: pageSize.value
    })
    
    if (searchQuery.value) {
      params.append('search', searchQuery.value)
    }
    
    if (dateRange.value && dateRange.value.length === 2) {
      params.append('startDate', dateRange.value[0])
      params.append('endDate', dateRange.value[1])
    }
    
    if (statusFilter.value) {
      params.append('status', statusFilter.value)
    }
    
    if (channelFilter.value) {
      params.append('channelId', channelFilter.value)
    }
    
    // 调用API获取订单
    const response = await api.get(`/orders?${params.toString()}`)
    
    if (response.data && response.data.status === 'success') {
      orders.value = response.data.data || []
      total.value = response.data.meta?.total || 0
    } else {
      ElMessage.error('获取订单失败')
      orders.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    orders.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 查看订单详情
const viewOrder = async (order) => {
  try {
    loading.value = true
    const response = await api.get(`/orders/${order.id}`)
    
    if (response.data && response.data.status === 'success') {
      currentOrder.value = response.data.data
      orderDialogVisible.value = true
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 更新订单状态
const updateOrderStatus = async (orderId, status) => {
  try {
    loading.value = true
    const response = await api.put(`/orders/${orderId}/status`, { status })
    
    if (response.data && response.data.status === 'success') {
      ElMessage.success(`订单状态已更新为${getStatusText(status)}`)
      
      // 更新列表中的订单状态
      const orderIndex = orders.value.findIndex(o => o.id === orderId)
      if (orderIndex !== -1) {
        orders.value[orderIndex].status = status
      }
      
      // 更新当前查看的订单状态
      if (currentOrder.value && currentOrder.value.id === orderId) {
        currentOrder.value.status = status
      }
    } else {
      ElMessage.error('更新订单状态失败')
    }
  } catch (error) {
    console.error('更新订单状态失败:', error)
    ElMessage.error('更新订单状态失败')
  } finally {
    loading.value = false
  }
}

// 打印订单
const printOrder = (order) => {
  ElMessage.success(`打印订单: ${order.orderNo}`)
  // 实际项目中应该调用打印API或使用打印插件
}



// 取消订单
const cancelOrder = (order) => {
  ElMessageBox.confirm(`确定要取消订单 ${order.orderNo} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateOrderStatus(order.id, 'cancelled')
  }).catch(() => {})
}

// 完成订单
const completeOrder = (order) => {
  ElMessageBox.confirm(`确定要将订单 ${order.orderNo} 标记为已完成吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateOrderStatus(order.id, 'completed')
  }).catch(() => {})
}

// 退款订单
const refundOrder = (order) => {
  ElMessageBox.confirm(`确定要为订单 ${order.orderNo} 退款吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateOrderStatus(order.id, 'refunded')
  }).catch(() => {})
}

// 导出订单
const exportOrder = async (order) => {
  try {
    // 获取完整订单信息
    const response = await api.get(`/orders/${order.id}`)
    
    if (response.data && response.data.status === 'success') {
      const orderData = response.data.data
      exportOrderToExcel([orderData])
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } catch (error) {
    console.error('导出订单失败:', error)
    ElMessage.error('导出订单失败')
  }
}

// 导出所有订单
const exportAllOrders = async () => {
  try {
    exporting.value = true
    
    // 构建查询参数，保持与当前筛选条件一致
    const params = new URLSearchParams({
      page: 1,
      limit: 1000 // 导出更多数据
    })
    
    if (searchQuery.value) {
      params.append('search', searchQuery.value)
    }
    
    if (dateRange.value && dateRange.value.length === 2) {
      params.append('startDate', dateRange.value[0])
      params.append('endDate', dateRange.value[1])
    }
    
    if (statusFilter.value) {
      params.append('status', statusFilter.value)
    }
    
    if (channelFilter.value) {
      params.append('channelId', channelFilter.value)
    }
    
    // 调用API获取订单
    const response = await api.get(`/orders?${params.toString()}`)
    
    if (response.data && response.data.status === 'success') {
      const ordersToExport = response.data.data || []
      if (ordersToExport.length === 0) {
        ElMessage.warning('没有符合条件的订单可以导出')
        return
      }
      
      // 导出订单数据到Excel
      exportOrderToExcel(ordersToExport)
    } else {
      ElMessage.error('获取订单数据失败')
    }
  } catch (error) {
    console.error('导出订单失败:', error)
    ElMessage.error('导出订单失败')
  } finally {
    exporting.value = false
  }
}

// 导出订单到Excel
const exportOrderToExcel = (ordersData) => {
  try {
    // 准备订单主表数据
    const ordersSheet = ordersData.map(order => ({
      '订单号': order.orderNo,
      '创建时间': formatDateTime(order.createdAt),
      '总金额': order.total.toFixed(2),
      '状态': getStatusText(order.status),
      '渠道': order.channel ? order.channel.name : '店内',
      '操作员': order.user ? order.user.name || order.user.username : '未知',
      '备注': order.note || ''
    }))
    
    // 准备订单明细数据
    const orderItemsData = []
    ordersData.forEach(order => {
      if (order.items && order.items.length > 0) {
        order.items.forEach(item => {
          orderItemsData.push({
            '订单号': order.orderNo,
            '商品名称': item.product ? item.product.name : '未知商品',
            '数量': item.quantity,
            '单价': item.price.toFixed(2),
            '小计': (item.price * item.quantity).toFixed(2)
          })
        })
      }
    })
    
    // 准备支付信息数据
    const paymentsData = []
    ordersData.forEach(order => {
      if (order.payments && order.payments.length > 0) {
        order.payments.forEach(payment => {
          paymentsData.push({
            '订单号': order.orderNo,
            '支付方式': getPaymentMethod(payment.method),
            '金额': payment.amount.toFixed(2),
            '支付状态': getPaymentStatusText(payment.status),
            '支付时间': formatDateTime(payment.createdAt)
          })
        })
      }
    })
    
    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new()
    
    // 添加订单主表
    const wsOrders = XLSX.utils.json_to_sheet(ordersSheet)
    XLSX.utils.book_append_sheet(wb, wsOrders, '订单列表')
    
    // 添加订单明细表
    if (orderItemsData.length > 0) {
      const wsItems = XLSX.utils.json_to_sheet(orderItemsData)
      XLSX.utils.book_append_sheet(wb, wsItems, '订单明细')
    }
    
    // 添加支付信息表
    if (paymentsData.length > 0) {
      const wsPayments = XLSX.utils.json_to_sheet(paymentsData)
      XLSX.utils.book_append_sheet(wb, wsPayments, '支付信息')
    }
    
    // 生成文件名
    const now = new Date()
    const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`
    const timeStr = `${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`
    const fileName = `订单数据_${dateStr}_${timeStr}.xlsx`
    
    // 导出Excel文件
    XLSX.writeFile(wb, fileName)
    
    ElMessage.success('订单导出成功')
  } catch (error) {
    console.error('导出Excel失败:', error)
    ElMessage.error('导出Excel失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取状态显示文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'paid': '已支付',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'paid': 'success',
    'completed': 'success',
    'cancelled': 'info',
    'refunded': 'danger'
  }
  return typeMap[status] || ''
}

// 获取支付方式文本
const getPaymentMethod = (method) => {
  const methodMap = {
    'cash': '现金',
    'wechat': '微信支付',
    'alipay': '支付宝',
    'mixed': '混合支付',
    'complimentary': '赠送'
  }
  return methodMap[method] || method
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  const statusMap = {
    'pending': '处理中',
    'completed': '已完成',
    'failed': '失败',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 获取支付状态类型
const getPaymentStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'completed': 'success',
    'failed': 'danger',
    'refunded': 'info'
  }
  return typeMap[status] || ''
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 处理日期变化
const handleDateChange = () => {
  currentPage.value = 1
  fetchOrders()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchOrders()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchOrders()
}

// 初始化
onMounted(() => {
  fetchChannels()
  fetchOrders()
})
</script>

<style scoped>
.admin-orders-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.header-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
}

.date-picker {
  width: 350px;
}

.status-select, .channel-select {
  width: 150px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-detail {
  padding: 10px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.order-info, .order-customer {
  flex: 1;
}

.order-summary {
  margin-top: 20px;
  text-align: right;
}

.total {
  font-size: 18px;
  color: #f56c6c;
}

.payment-info {
  margin-top: 30px;
}

.empty-data {
  text-align: center;
  padding: 40px 0;
}

.empty-data i {
  font-size: 50px;
  color: #909399;
}

.empty-data p {
  margin-top: 10px;
  color: #909399;
}

.export-btn {
  margin-right: 10px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
  font-size: 12px;
  padding: 4px 8px;
}
</style> 